<template>
  <dialog ref="videoDialog" style="width: 300px; height: 200px">
    <video ref="videoPlayer" controls></video>
    <div class="dialog-footer">
      <el-button type="primary" @click="closeVideoDialog">Close</el-button>
    </div>
  </dialog>

  <div class="container">
    <div class="loginPart">
      <div class="statistics-container">
        <el-statistic :title="'今日报警'" :value="todayAlarms" />
        <el-statistic :title="'历史报警'" :value="totalAlarms" />
        <el-statistic :title="'本月报警'" :value="currentMonthAlarms" />
        <el-statistic
            :title="'上月报警'"
            :value="previousMonthAlarms"
            :precision="0"
            :suffix="compareAlarms()"
            :value-style="{ color: compareColor() }"
        />
      </div>

      <div class="container">
        <div class="date-picker-container">
          <el-date-picker
              v-model="startDate"
              type="date"
              placeholder="开始日期"
          ></el-date-picker>
          <el-date-picker
              v-model="endDate"
              type="date"
              placeholder="结束日期"
              style="margin-left: 30px"
          ></el-date-picker>
          <el-button type="primary" @click="updateFilteredAlarms" style="margin-left: 30px">确认</el-button>
        </div>
      </div>
    </div>

    <div class="loginPart">
      <div class="charts-container">
        <div id="alarmTypeChart" style="width: 400px; height: 400px;"></div>
        <div id="alarmCountChart" style="width: 400px; height: 400px;"></div>
        <div id="cameraAlarmChart" style="width: 400px; height: 400px;"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import { showAlarmList } from "@/api/history";
import { ElMessage } from 'element-plus';

const videoDialog = ref<HTMLElement | null>(null);
const videoPlayer = ref<HTMLVideoElement | null>(null);
const list = ref([]);

const startDate = ref<Date | null>(null);
const endDate = ref<Date | null>(null);
const filteredList = ref([...list.value]);

const today = new Date().toISOString().split('T')[0];
const currentMonth = new Date().getMonth();
const currentYear = new Date().getFullYear();
const previousMonth = currentMonth === 0 ? 11 : currentMonth - 1;
const previousMonthYear = currentMonth === 0 ? currentYear - 1 : currentYear;

const fetchData = async () => {
  try {
    const response = await showAlarmList();
    list.value = response.data.list.map(item => ({
      ...item,
      alarm: reactive({
        camera_id: item.camera_id,
        time: item.time,
        type: item.type,
        video: item.video,
        info: item.info,
      }),
    }));
    updateFilteredAlarms();
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  fetchData();
});

const parseDateTime = (dateTimeStr: string): Date => {
  const [datePart, timePart] = dateTimeStr.split('_');
  const [year, month, day] = datePart.split('-').map(Number);
  const [hour, minute, second] = timePart.split('-').map(Number);
  return new Date(year, month - 1, day, hour, minute, second);
};

const todayAlarms = computed(() => {
  return list.value.filter(item => item.time.startsWith(today)).length;
});

const totalAlarms = computed(() => {
  return list.value.length;
});

const currentMonthAlarms = computed(() => {
  return list.value.filter(item => {
    const date = parseDateTime(item.time);
    return date.getMonth() === currentMonth && date.getFullYear() === currentYear;
  }).length;
});

const previousMonthAlarms = computed(() => {
  return list.value.filter(item => {
    const date = parseDateTime(item.time);
    return date.getMonth() === previousMonth && date.getFullYear() === previousMonthYear;
  }).length;
});

const compareAlarms = () => {
  const diff = currentMonthAlarms.value - previousMonthAlarms.value;
  return diff > 0 ? `↑${diff}` : `↓${Math.abs(diff)}`;
};

const compareColor = () => {
  const diff = currentMonthAlarms.value - previousMonthAlarms.value;
  return diff > 0 ? 'red' : 'green';
};

const updateFilteredAlarms = () => {
  if (startDate.value && endDate.value) {
    filteredList.value = list.value.filter(item => {
      const itemDate = parseDateTime(item.time).getTime();
      return itemDate >= startDate.value!.getTime() && itemDate <= endDate.value!.getTime();
    });
  } else {
    filteredList.value = [...list.value];
  }
  createCharts();
};

watch(list, () => {
  updateFilteredAlarms();
  createCharts();
}, { deep: true });

function toggleEditMode(index: number) {
  const item = list.value[index];
  let addr = item.video.replace('C:/Users/26368/Desktop/djangoProject1/algorithm/data/', 'http://localhost:8899/videos/');
  videoPlayer.value!.src = addr;
  videoDialog.value!.showModal();
  nextTick(() => {
    videoPlayer.value!.oncanplaythrough = function () {
      videoPlayer.value!.play();
    }
  });
}

function closeVideoDialog() {
  videoPlayer.value!.pause();
  videoPlayer.value!.currentTime = 0;
  videoDialog.value!.close();
}

// Function to create charts
function createCharts() {
  createAlarmTypeChart();
  createAlarmCountChart();
  createCameraAlarmChart();
}

function createAlarmTypeChart() {
  const alarmTypeChart = echarts.init(document.getElementById('alarmTypeChart')!);
  alarmTypeChart.setOption({
    title: {
      text: 'Alarm Type Distribution',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: 'Alarm Type',
        type: 'pie',
        radius: '50%',
        data: getUniqueAlarmTypes().map(type => ({
          value: filteredList.value.filter(item => item.type === type).length,
          name: type
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
}

function createAlarmCountChart() {
  const alarmCountChart = echarts.init(document.getElementById('alarmCountChart')!);
  alarmCountChart.setOption({
    title: {
      text: 'Alarm Count Over Time',
      left: 'center'
    },
    xAxis: {
      type: 'category',
      data: getTimeLabels()
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: getAlarmCountsOverTime(),
        type: 'line',
        smooth: true
      }
    ]
  });
}

function createCameraAlarmChart() {
  const cameraAlarmChart = echarts.init(document.getElementById('cameraAlarmChart')!);
  cameraAlarmChart.setOption({
    title: {
      text: 'Camera Alarm Count',
      left: 'center'
    },
    xAxis: {
      type: 'category',
      data: getUniqueCameraIds()
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: getCameraAlarmCounts(),
        type: 'bar'
      }
    ]
  });
}

// Helper functions to get data for charts
function getUniqueAlarmTypes() {
  return [...new Set(filteredList.value.map(item => item.type))];
}

function getAlarmTypeCounts() {
  const alarmTypes = getUniqueAlarmTypes();
  return alarmTypes.map(type => filteredList.value.filter(item => item.type === type).length);
}

function getTimeLabels() {
  return filteredList.value.map(item => item.time);
}

function getAlarmCountsOverTime() {
  const timeLabels = getTimeLabels();
  return timeLabels.map(time => filteredList.value.filter(item => item.time === time).length);
}

function getUniqueCameraIds() {
  return [...new Set(filteredList.value.map(item => item.camera_id))];
}

function getCameraAlarmCounts() {
  const cameraIds = getUniqueCameraIds();
  return cameraIds.map(id => filteredList.value.filter(item => item.camera_id === id).length);
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  margin: 20px auto;
}

.statistics-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.statistics-container {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-bottom: 20px;
}

.date-picker-container {
  display: flex;
  align-items: center;
}

.loginPart {
  width: 80%;
  padding: 40px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  margin-bottom: 40px;
}

.charts-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

#alarmTypeChart,
#alarmCountChart,
#cameraAlarmChart {
  width: 400px;
  height: 400px;
}

.dialog-footer {
  padding-left: 220px;
  margin-top: 10px;
}
</style>
